package models.campus;

import models.UUIDModel;
import models.admin.AdminUser;
import models.constants.DeletedStatus;
import models.contract.ContractRoom;
import models.enums.ContractStatus;
import play.Logger;
import play.db.jpa.JPA;
import util.common.ConvertUtil;
import util.common.UStringUtil;

import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 房间.
 */
@Entity
@Table(name = "bd_rooms")
public class Room extends UUIDModel {

    /**
     * 所属楼宇
     */
    @JoinColumn(name = "campus_building_id")
    @ManyToOne
    public Building building;

    /**
     * 所属区域
     */
    @JoinColumn(name = "campus_area_id")
    @ManyToOne
    public Area area;

    @Transient
    public String areaId;

    /**
     * 所属楼层
     */
    @JoinColumn(name = "campus_floor_id")
    @ManyToOne
    public Floor floor;

    @Transient
    public String floorId;

    /**
     * 房间号
     */
    @Column(name = "room_number", length = 10)
    public String roomNumber;

    /**
     * 信息审核状态
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "contract_status", length = 20)
    public ContractStatus contractStatus = ContractStatus.NO_CONTRACT;

    /**
     * 根据楼宇加载房间列表
     * @param buildingId
     * @return
     */
    public static List<Room> loadByBuilding(String buildingId) {
        return Room.find(" building.id = ? and deleted = ? order by roomNumber", buildingId, DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    public static Room findByRoomId(String id) {
        return Room.find(" id = ? and deleted = ? ", id, DeletedStatus.UN_DELETED).first();
    }

    /**
     * 删除房间
     * @param ids
     */
    public static void deleteRooms(String[] ids) {
        String idsStr = "'" + UStringUtil.concatStr("','", ids) + "'";
        String sqlUpdate = " update bd_rooms a set a.deleted = 1 where a.id in (" + idsStr + ")";
        JPA.em().createNativeQuery(sqlUpdate).executeUpdate();
    }

    /**
     * 更改某合同下房间的合同状态
     * @param contractId
     */
    public static void updateContractStatus(String contractId) {
        List<ContractRoom> contractRoomList = ContractRoom.find("contract.id = ? and deleted = ?", contractId, DeletedStatus.UN_DELETED).fetch();
        if (contractRoomList.size() > 0) {
            for (ContractRoom contractRoom : contractRoomList) {
                Room room = contractRoom.room;
                room.contractStatus = ContractStatus.NO_CONTRACT;
                room.save();
            }
        }

    }

    /**
     * 检查楼宇的房间是否已经存在
     * @param building
     * @param roomNumber
     * @return
     */
    public static Boolean checkByBuildingAndRoomNumber(Building building, String roomNumber) {
        return Room.count(" deleted = ? and building = ? and roomNumber = ? ", DeletedStatus.UN_DELETED, building, roomNumber) > 0;
    }


    //批量创建房间信息
    public static String insertRoom(List<Map<String, Object>> roomList, AdminUser loginUser) {
        String loseReason = "";
        for (int i = 0; i < roomList.size(); i++) {
            Map<String, Object> map = roomList.get(i);
            String campusName = ConvertUtil.toString(map.get("物业"));
            String buildingName = ConvertUtil.toString(map.get("楼宇"));
            String areaName = ConvertUtil.toString(map.get("单元"));
            String floorName = ConvertUtil.toString(map.get("楼层"));
            String roomNumber = ConvertUtil.toString(map.get("房间号"));
            Logger.info("--------------------物业: %s | 楼宇 : %s | 单元 :%s | 楼层 :%s | 房间号 :%s ", campusName, buildingName, areaName, floorName, roomNumber);

            Campus campus = Campus.findByName(campusName);
            //物业名称,物业,楼宇名称都不能为空,否则跳入下一个循环
            if (!campusName.isEmpty() && campus != null && !buildingName.isEmpty() && !roomNumber.isEmpty()) {
                //检索楼宇,如果楼宇不存在,则新建
                Building building = Building.findByNameAndCampus(campus, buildingName);
                if (building == null) {
                    building = new Building(campus, buildingName, loginUser).save();
                } else {
                    //同一楼宇同一房间号已经存在的,不可重复创建
                    if (Room.checkByBuildingAndRoomNumber(building, roomNumber)) {
                        loseReason += "\n第" + (i + 2) + "行: " + buildingName + " " + roomNumber + " 已经存在,不可重复创建;";
                        continue;
                    }
                }

                //检索单元
                Area area = null;
                if (!areaName.isEmpty()) {
                    area = Area.findByNameAndBuilding(building, areaName);
                    if (area == null) {
                        area = new Area(building, areaName, loginUser).save();
                    }
                }

                //检索楼层
                Floor floor = null;
                if (!floorName.isEmpty()) {
                    floor = Floor.findBybuildingAndName(building, floorName);
                    if (floor == null) {
                        floor = new Floor(building, floorName, loginUser).save();
                    }
                }

                //创建房间
                Room room = new Room();
                room.building = building;
                room.area = area;
                room.floor = floor;
                room.roomNumber = roomNumber;
                room.createUser = loginUser;
                room.createdAt = new Date();
                room.deleted = DeletedStatus.UN_DELETED;
                room.belongCompany = loginUser.organization != null ? loginUser.organization : null;
                room.save();

            } else {
                loseReason += "\n第" + (i + 2) + "行:";
                if (campusName.isEmpty() || campus == null)
                    loseReason += "物业不存在;";
                if (buildingName.isEmpty())
                    loseReason += "楼宇名称为空;";
                if (roomNumber.isEmpty())
                    loseReason += " 房间号为空;";
            }


        }
        Logger.info("创建失败记录:" + loseReason);
        return loseReason;
    }


}
